package com.smasher.update.component.download.sys

import android.content.Context
import android.net.Uri
import android.os.Build
import android.util.Log
import com.smasher.net.type.MimeTypeEnum
import com.smasher.update.R
import com.smasher.update.component.download.DownloadDelegate
import com.smasher.update.component.download.DownloadFinishListener
import com.smasher.update.component.download.DownloadHelper
import com.smasher.update.component.parse.ParseDelegate
import java.lang.ref.WeakReference

class DownloadImplSystem(context: Context) : DownloadDelegate {

    private val downloadHelper = DownloadHelper(context)

    private val downloadExecutor: DownloadExecutor = DownloadExecutor(context)
    private val defaultDownloading: String = context.getString(R.string.default_downloading)
    private var listener: DownloadFinishListener? = null

    private var weakReference = WeakReference(context)

    private val finishListener = object : DownloadFinishListener {
        override fun onDownload(id: Long) {
            Log.i(TAG, "onDownload: finish $id")
            listener?.onDownload(id)
        }
    }

    init {
        downloadExecutor.registerReceiveForDownLoad(context, finishListener)
    }

    override fun startDownload(parseDelegate: ParseDelegate): Long {
        val targetName = createTargetName()
        val request = downloadExecutor.buildDefaultRequest(
            parseDelegate.getDownLoadUrl(),
            parseDelegate.getUpdateTitle(),
            defaultDownloading,
            MimeTypeEnum.APK.getMimeType(),  //"application/vnd.android.package-archive",
            targetName
        )
        return downloadExecutor.download(request)
    }

    override fun addDownloadFinishListener(
        listener: DownloadFinishListener
    ) {
        this.listener = listener
    }


    override fun getDownloadUriById(id: Long): Uri? {
        return downloadExecutor.getUri(id)
    }

    override fun queryFinishedById(id: Long): Boolean {
        return downloadExecutor.queryFinishedById(id)
    }


    private fun createTargetName(): String {
        val time = System.currentTimeMillis()
        return ("TARGET_${downloadHelper.versionCode}_$time").toString() + ".apk"
    }

    override fun release() {
        weakReference.get()?.let {
            downloadExecutor.unregisterReceiveForDownload(it)
        }
        weakReference.clear()
    }

    companion object {
        const val TAG = "DownloadImplSystem"
    }
}
